﻿using Dyd.BaseService.Monitor.Domain.PlatformManage.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Web.Models;
using XXF.BasicService.CertCenter;
using XXF.Db;

namespace Web.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 签名
        /// </summary>
        /// <param name="paralist">需要进行签名的参数</param>
        /// <param name="appsecret">app密钥</param>
        /// <returns></returns>
        public static string GetSign(Dictionary<string, string> paralist, string appsecret)
        {
            if (paralist == null)
            {
                return null;
            }

            List<string> para = new List<string>();
            foreach (var a in paralist)
            {
                para.Add(a.Key + a.Value);
            }
            para.Sort();
            string centerstr = appsecret + string.Concat(para) + appsecret;

            return LibCrypto.MD5(centerstr);
        }

        [HttpGet]
        public ActionResult Login(string appid, string sign, string returnurl)
        {
            if (!string.IsNullOrEmpty(XXF.Db.DbConfig.GetConfig("CertCenterUrl")))//配置文件内包含认证中心地址，表明用统一认证
            {
                if (!string.IsNullOrEmpty(appid))
                {
                    XXF.BasicService.CertCenter.CertCenterProvider ccp = new XXF.BasicService.CertCenter.CertCenterProvider(XXF.BasicService.CertCenter.ServiceCertType.manage);
                    if (string.IsNullOrWhiteSpace(returnurl))
                    {
                        throw new Exception("returnurl错误！");
                    }
                    string appsecret = ccp.GetAppSecret(appid);
                    if (appsecret == "")
                    {
                        throw new Exception("appid不存在！");
                    }
                    Dictionary<string, string> para = new Dictionary<string, string>();//需要参加签名的参数对
                    para.Add("appid", appid);
                    para.Add("returnurl", returnurl);
                    if (sign != GetSign(para, appsecret))
                    {
                        throw new Exception("签名错误！");
                    }
                    if (User.Identity.IsAuthenticated)//已登录过
                    {
                        string[] tokens = User.Identity.Name.Split(',');
                        if (tokens.Count() > 1)
                        {
                            return RedirectToAction("index", "Cluster");
                        }
                    }
                }
            }
            return View();
        }

        //登录
        [HttpPost]
        public ActionResult Login(string appid, string sign, string returnurl, string username, string password, string validate)
        {
            try
            {
                returnurl = returnurl ?? "";
                username = username ?? "";
                password = password ?? "";
                validate = validate ?? "";
                ViewBag.username = username;
                string token = "";//认证中心返回的授权码
                if (!string.IsNullOrEmpty(XXF.Db.DbConfig.GetConfig("CertCenterUrl")))//配置文件内包含认证中心地址，表明用统一认证
                {
                    XXF.BasicService.CertCenter.CertCenterProvider ccp = new XXF.BasicService.CertCenter.CertCenterProvider(XXF.BasicService.CertCenter.ServiceCertType.manage);
                    if (!string.IsNullOrEmpty(appid))
                    {   //外部授权
                        if (returnurl.Length < 2)
                        {
                            throw new Exception("returnurl错误！");
                        }
                        string appsecret = ccp.GetAppSecret(appid);
                        if (appsecret == "")
                        {
                            throw new Exception("appid不存在！");
                        }
                        Dictionary<string, string> para = new Dictionary<string, string>();//需要参加签名的参数对
                        para.Add("appid", appid);
                        para.Add("returnurl", returnurl);
                        if (sign != GetSign(para, appsecret))
                        {
                            throw new Exception("签名错误！");
                        }
                    }
                    AuthToken re = ccp.Login(username, password);
                    if (re != null)
                    {
                        throw new Exception("登陆出错,请咨询管理员" + ccp.result.msg);
                    }
                }
                
                tb_user_model user = Common.GetUserName(username);
                #region 6写auth Cookie
                if (user == null)
                    throw new Exception("用户在平台中未开权限。");
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(user.id + " " + user.username + "," + token + " " + user.userrole, false, (int)FormsAuthentication.Timeout.TotalMinutes);
                string enticket = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookieofau = new HttpCookie(FormsAuthentication.FormsCookieName, enticket);
                Response.AppendCookie(cookieofau);
                #endregion
                return RedirectToAction("index", "TimeWatchLogApiDayReport", new { userid = user.id });
            }
            catch (Exception exp)
            {
                ModelState.AddModelError("", "登陆出错,请咨询管理员。错误信息:" + exp.Message);
                return View();
            }
        }

        //登出
        public ActionResult Logout(string returnurl)
        {
            if (User.Identity.IsAuthenticated)
            {
                XXF.BasicService.CertCenter.CertCenterProvider ccp = new XXF.BasicService.CertCenter.CertCenterProvider(XXF.BasicService.CertCenter.ServiceCertType.manage);
                HttpCookie authcookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authcookie.Value);
                string userid = ticket.Name.Split(' ').FirstOrDefault();
                ccp.LogOut(ticket.Name.Split(',').LastOrDefault());
                FormsAuthentication.SignOut();
            }
            if (string.IsNullOrEmpty(returnurl))
                return Redirect("/Login/Login");
            else
                return Redirect(returnurl);
        }

    }
}
